<?php

namespace App\HttpController\Wx\Oauth;


use App\Common\Sys;
use App\Common\WX\Wx;
use App\Common\WX\WxWord;
use App\HttpController\ControllerBase;
use App\X\EHelper;
use XWX\Common\H;

class OauthCallback extends ControllerBase
{
    public function index()
    {
        $code = $this->reqParam('code');
        $state = $this->reqParam('state'); //获取用户信息,0否，1是|word

        $dev = $this->reqParam('dev');


        $state_data = explode('|', $state);
        if (count($state_data) < 2)
        {
            return $this->funcWriteErr(-119, '参数异常：state');
        }


        $get_userinfo = $state_data[0] == 1;
        $word = $state_data[1];

        $config = $this->funcGetX__config();

        $app_wx = Wx::funcIns($config);
        $r = $app_wx->funcOAuthOpenid($code, $get_userinfo);
        if ($r->err())
        {
            return $this->funcWriteErrR($r);
        }


        $wx_word = new WxWord($word);
        $app_id = $wx_word->app();
        $key = $wx_word->keyNum();

        $openid = $r->getData('openid');

        $x_key = 'wx_oauth:' . EHelper::funcGetID();

        $redis_data = [
            'getUserID' => $openid,
            'word' => $word,
            'x' => $this->funcGetX(),
        ];
        $this->redis()->setEx($x_key, 1 * 60, H::funcToStr($redis_data));

        $app_root = Sys::funcAppRoot();
        $redirect_url = "{$app_root}{$app_id}/web_{$key}/sys/web?x_key={$x_key}";
        if (H::funcStrHasAnyText($dev))
        {
            //调试用
            $redirect_url .= "&dev={$dev}";
        }


        $this->response()->redirect($redirect_url);
//        $this->commonR()->setData('url', $redirect_url);
//        $this->funcWriteCommonR();
    }
}